<template>
    <div id="charts">
        <el-form :inline="true" class="demo-form-inline" v-model="customList" label-position="right" label-width="130px" style="margin-bottom: 20px;">
            <el-select v-model="customList.user" :disabled="!jurisdiction.qureyAll">
                <el-option v-for="item in usersData" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
            <el-date-picker
                v-model="customList.dateTime"
                type="datetimerange"
                :picker-options="pickerOptions2"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
            </el-date-picker>
            <el-button type="primary" @click="openCharts">查询</el-button>
        </el-form>
        <el-button type="danger" @click="openPieChart" style="position: fixed;top: 80px;right: 10px;">饼图</el-button>

        <div id="chartCustom" ref="chartCustom"  :style="customStyle"></div>
        <el-dialog title="饼图" width="1050px" top="80px" :visible.sync="isDialog" :close-on-click-modal="false" style="padding-bottom: 15px;">
            <div style="width: 100%;overflow: hidden;margin-top: 20px;">
                <div id="chartPieFinish" ref="chartPieFinish" :style="pieStyle"></div>
                <div id="chartPieType" ref="chartPieType"  :style="pieStyle"></div>
            </div>
            <div slot="footer"></div>
        </el-dialog>

    </div>
</template>

<script>
    import echarts from 'echarts';
    export default {
        name: 'counts',
        data() {
            let token = sessionStorage.getItem("tokenId");
            let menuId = sessionStorage.getItem('menuId');
            let userId = parseInt(sessionStorage.getItem('userId'));
            let date = new Date();
            let start = date.setDate(new Date(date.setHours(0, 0, 0, 0)).getDate() - 20 );
            return {
                pickerOptions2: {
                    shortcuts: [
                        {
                            text: '最近一周',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                                picker.$emit('pick', [start, end]);
                            }
                        },
                        {
                            text: '最近一个月',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                                picker.$emit('pick', [start, end]);
                            }
                        },
                        {
                            text: '最近三个月',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                                picker.$emit('pick', [start, end]);
                            }
                        }
                    ]
                },
                tokenId: token,
                menuId: menuId,
                usersData: [],
                jurisdiction:{
                    qureyAll:true,
                },

                //甘特图
                customList: {
                    user: userId,
                    dateTime: [start,  new Date()],
                },
                customStyle:{
                    width: '100%',
                    height: (document.documentElement.clientHeight - 160) + 'px'
                },
                customData: [],
                chartCustom: null,


                isDialog:false,
                //饼图任务完成
                pieStyle:{
                    width: '49%',
                    height: (document.documentElement.clientHeight - 240) + 'px',
                    marginRight:'1%',
                },
                chartPieFinish:null,
                pieFinishData: [],

                //饼图任务类型
                chartPieType:null,
                pieTypeData: [],





            }
        },
        created() {
            this.getJurisdiction();
            this.getUsersData();
            this.getCustomData();
        },
        methods: {

            getJurisdiction() {
                let _this = this;
                this.$http({
                    url: '/api/adscm/system/menu/getMenuAllSrc/' + _this.menuId + '?tokenId=' + _this.tokenId,
                    method: 'post',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                }).then(function (res) {
                    if (res.data.statusCode == 200) {
                        for (let i = 0; i < res.data.content.length; i++) {
                            let item = res.data.content[i];
                            _this.jurisdiction[item.component] = item.menuShow;
                        }
                    } else {
                        _this.$message.error(res.data.desc);
                    }
                }).catch(function (catchres) {
                    _this.$message.error("加载失败！请重新加载...");
                })
            },
            getUsersData() {
                let _this = this;
                this.$http({
                    url: '/api/adscm/operation/taskManagerAnalysis/queryUser?tokenId=' + _this.tokenId,
                    method: 'post',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                }).then(function (res) {
                    if (res.data.statusCode == 200) {
                        _this.usersData = res.data.content;
                    } else {
                        _this.$message.error(res.data.desc);
                    }
                }).catch(function (catchres) {
                    _this.$message.error("加载失败！请重新加载...");
                })
            },
            openCharts(){
                this.getCustomData();
            },

            //甘特图
            getCustomData() {
                let _this = this;

                let loading = this.$loading({
                    target: document.querySelector(".wrapper > .content-box"),
                    lock: true,
                    text: '正在努力加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.8)'
                });
                let start = _this.timestampToTime(_this.customList.dateTime[0]);
                let end = _this.timestampToTime(_this.customList.dateTime[1]);
                this.$http({
                    url: '/api/adscm/operation/taskManagerAnalysis/queryTaskManager/' + _this.customList.user + '/' + start + '/' + end + '?tokenId=' + _this.tokenId,
                    method: 'post',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                }).then(function (res) {
                    if (res.data.statusCode == 200) {
                        _this.customData = res.data.content;
                        _this.drawCustom();
                    } else {
                        _this.$message.error(res.data.desc);
                    }
                    loading.close();
                }).catch(function (catchres) {
                    _this.$message.error("加载失败！请重新加载...");
                    loading.close();
                })
            },
            drawCustom() {
                let _this = this;
                this.chartCustom = echarts.init(document.getElementById('chartCustom'));
                function renderItem(params, api) {
                    let categoryIndex = api.value(0);
                    let start = api.coord([api.value(1), categoryIndex]);
                    let end = api.coord([api.value(2), categoryIndex]);
                    let height = api.size([0, 1])[1] * 0.6;

                    let rectShape = echarts.graphic.clipRectByRect({
                        x: start[0],
                        y: start[1] - height / 2,
                        width: end[0] - start[0],
                        height: height
                    }, {
                        x: params.coordSys.x,
                        y: params.coordSys.y,
                        width: params.coordSys.width,
                        height: params.coordSys.height
                    });

                    return rectShape && {
                        type: 'rect',
                        shape: rectShape,
                        style: api.style()
                    };
                }
                let legendData=[],yAxisData =[],seriesData=[];


                console.log( _this.customData )
                debugger;
                for (let i = 0; i < _this.customData.length; i++) {

                    let item = _this.customData[i];
                    yAxisData.push( item.creatDate.substr(0,10) );
                    legendData.push({
                        name: item.isRepeat == 1 ? "时间重叠" :(item.state == 0 ? "每日任务" : (item.state == 1 ? "发放任务" :"")),
                        icon: 'circle'
                    });

                    seriesData.push({
                        name: item.isRepeat == 1 ? "时间重叠" :(item.state == 0 ? "每日任务" : (item.state == 1 ? "发放任务" :"")),
                        type: "custom",
                        encode: {x: [1, 2], y: 0},
                        renderItem: renderItem,
                        data: [
                            {
                                name: item.state == 0 ? "每日任务" : (item.state == 1 ? "发放任务" : ''),
                                value: [
                                    item.creatDate.substr(0,10),
                                    '2019-01-01 ' + item.startDate.substr(11),
                                    '2019-01-01 ' + item.endDate.substr(11),
                                    item.creatTime,
                                    item.creatDate,
                                    item.taskDescription,
                                    item.isNowTime,
                                    item.useTime,
                                ]
                            }
                        ]
                    })
                }
                debugger;
                this.chartCustom.clear();
                this.chartCustom.setOption({
                    color: [
                        '#409eff',
                        '#e6a23c',
                        '#67c23a',
                    ],
                    title: {
                        text: '工作统计',
                        textStyle: {
                            color: '#000',
                            fontSize: 17,
                            fontFamily: '微软雅黑'
                        }
                    },
                    tooltip: {
                        backgroundColor: "#F6F6F6",
                        borderWidth: 1,
                        borderColor: "rgba(0,0,0,.3)",
                        triggerOn: "click",
                        confine: true,
                        enterable: true,
                        transitionDuration: 0,
                        textStyle: {color: "#333"},
                        extraCssText: 'box-shadow: 0 0 5px 1px rgba(255, 255, 255, 0.3);',
                        formatter: function (params) {
                            console.log(  params.value  )
                            return '<div style="width: 300px;">' + params.value[0] +
                                '<P>开始时间：' + params.value[1].substr(11)+'</P>' +
                                '<P>结束时间：' + params.value[2].substr(11)+'</P>' +
                                '<P>耗时：' + params.value[7]+'</P>' +
                                '<P>是否实时时间：'+ (params.value[6] == 0 ? '否' : (params.value[6] == 1 ? '是' : '')) +'</P>' +
                                '<P style="width: 280px;white-space:normal; word-break:break-all;">任务名称：'+params.value[5] +'</P>' +
                                '</div>';
                        }
                    },
                    dataZoom: [
                        {
                            type: 'slider',
                            filterMode: 'weakFilter',
                            showDataShadow: true,
                            bottom: 10,
                            height: 5,
                            borderColor: 'transparent',
                            backgroundColor: '#e2e2e2',
                            handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z',
                            handleSize: 20,
                            handleStyle: {
                                shadowBlur: 6,
                                shadowOffsetX: 1,
                                shadowOffsetY: 2,
                                shadowColor: '#aaa'
                            },
                            labelFormatter: ''
                        },
                        {
                            type: 'inside',
                            filterMode: 'weakFilter'
                        }
                    ],
                    legend: {
                        left:100,
                        itemWidth: 14,
                        data:legendData
                    },
                    grid: {left: 100, right: 40, bottom: 50,top:30},
                    xAxis: {
                        type: 'time',
                        splitLine: {show: false},
                        axisLabel: {
                            formatter: function (params) {
                                return _this.timestampToTime(params).substr(10)
                            }
                        }
                    },
                    yAxis: {
                        data: _this.unique(yAxisData)
                    },
                    series: seriesData
                });
            },



            openPieChart(){
               this.isDialog = true;
                this.getPieFinishData();
                this.getPieTypeData();
            },


            //饼图 任务完成
            getPieFinishData() {
                let _this = this;
                let start = _this.timestampToTime(_this.customList.dateTime[0]);
                let end = _this.timestampToTime(_this.customList.dateTime[1]);
                this.$http({
                    url: '/api/adscm/operation/taskManagerAnalysis/querySelfWorthPieChart/' + _this.customList.user + '/' + start + '/' + end + '?tokenId=' + _this.tokenId,
                    method: 'post',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                }).then(function (res) {
                    if (res.data.statusCode == 200) {
                        _this.pieFinishData = res.data.content;
                        _this.drawPieFinish();
                    } else {
                        _this.$message.error(res.data.desc);
                    }
                }).catch(function (catchres) {
                    _this.$message.error("加载失败！请重新加载...");
                })
            },
            drawPieFinish() {
                let _this = this;
                this.chartPieFinish = echarts.init(document.getElementById('chartPieFinish'));
                let start = _this.timestampToTime(_this.customList.dateTime[0]).substr(0,10);
                let end = _this.timestampToTime(_this.customList.dateTime[1]).substr(0,10);

                let legendData = [],seriesData=[];
                for (let i = 0;i<_this.pieFinishData.length;i++) {
                    let item = _this.pieFinishData[i];
                    legendData.push({
                        name: item.type + '（'+item.use+'件）',
                        icon:'circle'
                    });
                    seriesData.push({
                        value:item.use,
                        name:item.type + '（'+item.use+'件）',
                        itemData:item
                    });
                }

                this.chartPieFinish.clear();
                this.chartPieFinish.setOption({
                    color: [
                        '#409eff',
                        '#e6a23c',
                        '#67c23a',
                        '#909399',
                        '#f56c6c',
                        '#e9b434',
                        '#e971ba',
                        '#27e9e4',
                    ],
                    title : {
                        text: '任务评价占比',
                        textStyle: {
                            color: '#000',
                            fontSize: 17,
                            fontFamily: '微软雅黑'
                        }
                    },
                    tooltip: {
                        backgroundColor: "#F6F6F6",
                        borderWidth: 1,
                        borderColor: "rgba(0,0,0,.3)",
                        triggerOn: "click",
                        confine: true,
                        enterable: true,
                        transitionDuration: 0,
                        textStyle: {color: "#333"},
                        extraCssText: 'box-shadow: 0 0 5px 1px rgba(255, 255, 255, 0.3);',
                        formatter: function (params) {
                            console.log( params.data.itemData )
                            let item = params.data.itemData;

                            // console.log( item )

                            // return '<div>' + item.taskName +  +
                            //         '<P><em>耗时占比：</em><span>'+ item.percent +'</span></P>' +
                            //     '<P><em>耗时：</em><span>'+((item.useTime/60000).toFixed(2))+'分钟</span></P>' +
                            //     '<P><em>开始时间：</em><span>'+item.startDate+'</span></P>' +
                            //     '<P><em>结束时间：</em><span>'+item.endDate+'</span></P>' +
                            //     '</div>';
                        }
                    },
                    legend: {
                        orient: 'vertical',
                        top: 40,
                        left: 'left',
                        itemWidth: 14,
                        data:legendData
                    },
                    series : [
                        {
                            name: start + ' - ' + end,
                            type: 'pie',
                            radius : '75%',
                            center: ['50%', '70%'],
                            data:seriesData,
                            label: {
                                normal: {

                                    position: 'inner',
                                    formatter: '{per|{d}%}  ',
                                    rich: {
                                        b: {
                                            fontSize: 16,
                                            lineHeight: 33
                                        },
                                        per: {
                                            color: '#eee',
                                        }
                                    }

                                }
                            },
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            }
                        }
                    ]
                });
            },


            //饼图 任务类型
            getPieTypeData() {
                let _this = this;
                let start = _this.timestampToTime(_this.customList.dateTime[0]);
                let end = _this.timestampToTime(_this.customList.dateTime[1]);
                this.$http({
                    url: '/api/adscm/operation/taskManagerAnalysis/queryPieChartTime/' + _this.customList.user + '/' + start + '/' + end + '?tokenId=' + _this.tokenId,
                    method: 'post',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                }).then(function (res) {
                    if (res.data.statusCode == 200) {
                        _this.pieTypeData = res.data.content;
                        _this.drawPieType();
                    } else {
                        _this.$message.error(res.data.desc);
                    }
                }).catch(function (catchres) {
                    _this.$message.error("加载失败！请重新加载...");
                })
            },
            drawPieType() {
                let _this = this;
                this.chartPieType = echarts.init(document.getElementById('chartPieType'));
                let start = _this.timestampToTime(_this.customList.dateTime[0]).substr(0,10);
                let end = _this.timestampToTime(_this.customList.dateTime[1]).substr(0,10);
                let legendData = [],seriesData=[];
                for (let i = 0;i<_this.pieTypeData.length;i++) {
                    let item = _this.pieTypeData[i];
                    legendData.push({
                        name: item.taskName + '（'+((item.useTime/60000).toFixed(2))+'分钟）',
                        icon:'circle'
                    });
                    seriesData.push({
                        value:item.useTime,
                        name:item.taskName+ '（'+((item.useTime/60000).toFixed(2))+'分钟）',
                        itemData:item
                    });
                }

                this.chartPieType.clear();
                this.chartPieType.setOption({
                    color: [
                        '#409eff',
                        '#e6a23c',
                        '#67c23a',
                        '#909399',
                        '#f56c6c',
                        '#e9b434',
                        '#e971ba',
                        '#27e9e4',
                    ],
                    title : {
                        text: '任务类型占比',
                        textStyle: {
                            color: '#000',
                            fontSize: 17,
                            fontFamily: '微软雅黑'
                        }
                    },
                    tooltip: {
                        backgroundColor: "#F6F6F6",
                        borderWidth: 1,
                        borderColor: "rgba(0,0,0,.3)",
                        triggerOn: "click",
                        confine: true,
                        enterable: true,
                        transitionDuration: 0,
                        textStyle: {color: "#333"},
                        extraCssText: 'box-shadow: 0 0 5px 1px rgba(255, 255, 255, 0.3);',
                        formatter: function (params) {
                            // console.log( params.data.itemData )
                            let item = params.data.itemData;
                            return '<div>' + item.taskName  +
                                '<p><em>耗时占比：</em><span>'+ item.percent +'</span></p>' +
                                '<p><em>耗时：</em><span>'+((item.useTime/60000).toFixed(2))+'分钟</span></p>' +
                                '<p><em>开始时间：</em><span>'+item.startDate+'</span></p>' +
                                '<p><em>结束时间：</em><span>'+item.endDate+'</span></p>' +
                                '</div>';
                        }
                    },
                    legend: {
                        type: 'scroll',
                        orient: 'vertical',
                        top: 40,
                        bottom: document.documentElement.clientHeight - 500,
                        left: 'left',
                        itemWidth: 14,
                        data:legendData
                    },
                    series : [
                        {
                            name: start + ' - ' + end,
                            type: 'pie',
                            radius : '75%',
                            center: ['50%', '70%'],
                            data:seriesData,
                            label: {
                                normal: {

                                    position: 'inner',
                                    formatter: '{per|{d}%}  ',
                                    // formatter: '  {c} {per|{d}%}  ',
                                    rich: {
                                        b: {
                                            fontSize: 16,
                                            lineHeight: 33
                                        },
                                        per: {
                                            color: '#eee',
                                        }
                                    }

                                }
                            },
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            }
                        }
                    ]
                });
            },


            unique(Array) {
                let res = [];
                let json = {};
                for (let i = 0; i < Array.length; i++) {
                    if (!json[Array[i]]) {
                        res.push(Array[i]);
                        json[Array[i]] = 1;
                    }
                }
                return res;
            },
            timestampToTime(timestamp) {
                if (timestamp) {
                    let date = new Date(timestamp);
                    let Y = date.getFullYear() + '-';
                    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
                    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + " ";
                    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ":";
                    let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":";
                    let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                    return timestamp ? Y + M + D + h + m + s : '';
                } else {
                    return '';
                }
            },
        }
    }

</script>

<style scoped>

    #charts{
        /*width: 100%;*/
        /*height: 100%;*/
        /*background: #0F3357;*/
    }

    #charts #chartCustom,
    #charts #chartPieType,
    #charts #chartPieFinish{
        border:1px solid #ececec;
        padding:5px;
        box-sizing: border-box;
    }

    #charts #chartPieType,
    #charts #chartPieFinish{
        float: left;
    }

</style>
